package com.itfreer.content.task;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;

import com.itfreer.content.R;
import com.itfreer.content.notice.MessageActivity;
import com.itfreer.core.collection.SerializableMap;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.TextView;
import com.itfreer.ui.base.checkbox.CheckBox;
import com.itfreer.ui.base.datetime.DatePickerDialog;
import com.itfreer.ui.base.datetime.DatePickerView;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务管理
 */
public class TaskActivity extends BaseActivity implements DatePickerView.OnDateSetListener {

    private LinearLayout task_content;
    private LoadTaskHandler loadTaskHandler;

//    private TextView task_state_all;
//    private View task_state_all_1;
//
//    private TextView task_state_01;
//    private View task_state_01_1;
//
//    private TextView task_state_02;
//    private View task_state_02_1;
//
//    private TextView task_state_03;
//    private View task_state_03_1;

    private DatePickerView beginPicker;
    private DatePickerView endPicker;

    private String beginDateStr;
    private String endDateStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);

        // 返回
        TextView back =(TextView)findViewById(R.id.taskBack);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });

        task_content =(LinearLayout)findViewById(R.id.task_content);
        loadTaskHandler = new LoadTaskHandler();

        // 跳转到任务统计
        com.itfreer.ui.base.TextView total =(TextView)findViewById(R.id.taskFormTotal);
        total.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("entity", null);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(TaskActivity.this, TaskTotalActivity.class);
                // 启动一个新的Activity
                startActivity(intent);
            }
        });

//        task_state_all =(TextView)findViewById(R.id.task_state_all);
//        task_state_all_1 =(View)findViewById(R.id.task_state_all_1);
//
//        task_state_01 =(TextView)findViewById(R.id.task_state_01);
//        task_state_01_1 =(View)findViewById(R.id.task_state_01_1);
//
//        task_state_02 =(TextView)findViewById(R.id.task_state_02);
//        task_state_02_1 =(View)findViewById(R.id.task_state_02_1);
//
//        task_state_03 =(TextView)findViewById(R.id.task_state_03);
//        task_state_03_1 =(View)findViewById(R.id.task_state_03_1);

        filter(null);

        // 打开时同步一次
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(TaskService.instance.syn()){
                    // 重新加载
                    Message msg = new Message();
                    Bundle b = new Bundle();
                    msg.setData(b);
                    loadTaskHandler.sendMessage(msg);
                }
            }
        }).start();
    }

    private class LoadTaskHandler extends Handler {
        public LoadTaskHandler() {
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            filter(null);
        }
    }

    public void filterAll(View v) {
        filter(null);
    }

    public void filter01(View v) {
        filter("01");
    }

    public void filter02(View v) {
        filter("02");
    }

    public void filter03(View v) {
        filter("03");
    }

    public void filter(String state){
//        task_state_all.setTextColor(Color.parseColor("#303059"));
//        task_state_all_1.setVisibility(View.GONE);
//
//        task_state_01.setTextColor(Color.parseColor("#303059"));
//        task_state_01_1.setVisibility(View.GONE);
//
//        task_state_02.setTextColor(Color.parseColor("#303059"));
//        task_state_02_1.setVisibility(View.GONE);
//
//        task_state_03.setTextColor(Color.parseColor("#303059"));
//        task_state_03_1.setVisibility(View.GONE);
//
//        if(state==null || state.equals("")){
//            task_state_all.setTextColor(Color.parseColor("#ffffff"));
//            task_state_all_1.setVisibility(View.VISIBLE);
//        } else if (state.equals("01")){
//            task_state_01.setTextColor(Color.parseColor("#ffffff"));
//            task_state_01_1.setVisibility(View.VISIBLE);
//        } else if (state.equals("02")){
//            task_state_02.setTextColor(Color.parseColor("#ffffff"));
//            task_state_02_1.setVisibility(View.VISIBLE);
//        } else if (state.equals("03")){
//            task_state_03.setTextColor(Color.parseColor("#ffffff"));
//            task_state_03_1.setVisibility(View.VISIBLE);
//        }

        loadTask(null);
    }

    /**
     * 加载信息
     */
    private void loadTask(Map map){
        task_content.removeAllViews();
        List<TaskEntity> tasks = TaskService.instance.getEntitys(map);
        if(tasks==null || tasks.size()<=0){
            return;
        }

        for(TaskEntity task : tasks){
            loadMsg(task);
        }
    }

    private void loadMsg(TaskEntity task) {
        final float scale = this. getResources().getDisplayMetrics().density;
        int dp1 = (int) (1 * scale + 0.5f);
        int dp6 = (int) (6 * scale + 0.5f);
        int dp10 = (int) (10 * scale + 0.5f);
        int dp15 = (int) (15 * scale + 0.5f);
        int dp16 = (int) (16 * scale + 0.5f);
        int dp20 = (int) (20 * scale + 0.5f);
        int dp22 = (int) (22 * scale + 0.5f);
        int dp25 = (int) (25 * scale + 0.5f);

        LinearLayout item = new LinearLayout(TaskActivity.this);
        LinearLayout.LayoutParams itemParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        itemParams.setMargins(dp15, dp10, dp15, 0);
        item.setLayoutParams(itemParams);
        item.setOrientation(LinearLayout.VERTICAL);
        item.setBackgroundResource(R.drawable.search_bg);

        TextView title = new TextView(TaskActivity.this);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp22);
        titleParams.setMargins(dp25, dp25,0,0);
        title.setLayoutParams(titleParams);
        title.setGravity(Gravity.CENTER|Gravity.LEFT);
        title.setTextColor(Color.parseColor("#4a4a4a"));
        title.setTextSize(18);
        title.setText(task.getTaskTheme());
        item.addView(title);

        LinearLayout firstChild = new LinearLayout(TaskActivity.this);
        LinearLayout.LayoutParams firstChildParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        firstChildParams.setMargins(dp25, dp10, dp15, 0);
        firstChild.setLayoutParams(firstChildParams);
        firstChild.setOrientation(LinearLayout.HORIZONTAL);

        TextView pushDate = new TextView(TaskActivity.this);
        LinearLayout.LayoutParams pushDateParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp16);
        pushDateParams.weight = 1;
//        pushDateParams.setMargins(dp25, dp6,0,0);
        pushDate.setLayoutParams(pushDateParams);
        pushDate.setGravity(Gravity.LEFT);
        pushDate.setTextColor(Color.parseColor("#bcbcbc"));
        pushDate.setTextSize(14);
        pushDate.setText("任务年份:" + (task.getYear() != null?task.getYear():"暂无"));

        firstChild.addView(pushDate);

        TextView taskType = new TextView(TaskActivity.this);
        LinearLayout.LayoutParams taskTypeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp16);
        taskTypeParams.weight = 1;
//        taskTypeParams.setMargins(dp25, dp6,0,0);
        taskType.setLayoutParams(taskTypeParams);
        taskType.setGravity(Gravity.LEFT);
        taskType.setTextColor(Color.parseColor("#bcbcbc"));
        taskType.setTextSize(14);
        taskType.setText("任务类型:" + (task.getTaskTypeName()!=null?task.getTaskTypeName():"暂无"));

        firstChild.addView(taskType);

        item.addView(firstChild);

        LinearLayout secondChild = new LinearLayout(TaskActivity.this);
        LinearLayout.LayoutParams secondChildParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        secondChildParams.setMargins(dp25, dp10, dp15, 0);
        secondChild.setLayoutParams(secondChildParams);
        secondChild.setOrientation(LinearLayout.HORIZONTAL);

        TextView cpushDate = new TextView(TaskActivity.this);
        LinearLayout.LayoutParams cpushDateParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp16);
        cpushDateParams.weight = 1;
//        pushDateParams.setMargins(dp25, dp6,0,0);
        cpushDate.setLayoutParams(pushDateParams);
        cpushDate.setGravity(Gravity.LEFT);
        cpushDate.setTextColor(Color.parseColor("#bcbcbc"));
        cpushDate.setTextSize(14);
        cpushDate.setText("巡查周期:" + (task.getCycleName()!=null?task.getCycleName():"暂无"));

        secondChild.addView(cpushDate);

        TextView ctaskType = new TextView(TaskActivity.this);
        LinearLayout.LayoutParams ctaskTypeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp16);
        ctaskTypeParams.weight = 1;
//        taskTypeParams.setMargins(dp25, dp6,0,0);
        ctaskType.setLayoutParams(ctaskTypeParams);
        ctaskType.setGravity(Gravity.LEFT);
        ctaskType.setTextColor(Color.parseColor("#bcbcbc"));
        ctaskType.setTextSize(14);
        ctaskType.setText("巡查次数:" + (task.getCount()!=null?task.getCount():"暂无"));

        secondChild.addView(ctaskType);

        item.addView(secondChild);

        TextView content = new TextView(TaskActivity.this);
        LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        contentParams.setMargins(dp25, dp20, dp25, dp25);
        content.setLayoutParams(contentParams);
        content.setGravity(Gravity.CENTER|Gravity.LEFT);
        content.setTextColor(Color.parseColor("#e6725c"));
        content.setTextSize(16);
        content.setText(task.getContent());
        item.addView(content);

        View splitView = new View(TaskActivity.this);
        LinearLayout.LayoutParams splitViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp1);
        splitViewParams.setMargins(dp25, dp20, dp25,0);
        splitView.setLayoutParams(splitViewParams);
        splitView.setBackgroundColor(Color.parseColor("#e3e3e3"));
        item.addView(splitView);

        CheckBox option = new CheckBox(TaskActivity.this);
        LinearLayout.LayoutParams optionParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp22);
        optionParams.setMargins(dp25, dp20, 0, dp20);
        option.setLayoutParams(optionParams);
        option.setGravity(Gravity.CENTER|Gravity.LEFT);
        option.setTextColor(Color.parseColor("#66708d"));
        option.setTextSize(16);
        option.setText("已完成");
        option.setChecked("1".equals(task.getStatus()));
        option.setTag(task);
        option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox checkBox = (CheckBox) view;
                TaskEntity taskEntity = (TaskEntity) checkBox.getTag();
                if (checkBox.isChecked()) {
                    taskEntity.setStatus("1");
                    System.out.println("选中");
                } else {
                    taskEntity.setStatus("2");
                    System.out.println("取消选中");
                }

//                Intent intent = new Intent();
//                intent.putExtra("datas", (Serializable) taskEntity);
//                setResult(RESULT_OK, intent);
            }
        });
        item.addView(option);

        item.setTag(task);
        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LinearLayout linearLayout = (LinearLayout) view;
                TaskEntity taskEntity = (TaskEntity) linearLayout.getTag();

                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("entity", taskEntity);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(TaskActivity.this, TaskFormActivity.class);
                // 启动一个新的Activity
                startActivity(intent);
            }
        });

        task_content.addView(item);

    }

    @Override
    public void onDateSet(String fieldName, int startYear, int startMonthOfYear, int startDayOfMonth){
        if ("begin".equals(fieldName)) {
            beginDateStr = startYear + "-" + startMonthOfYear + "-" + startDayOfMonth;
        } else if ("end".equals(fieldName)) {
            endDateStr = startYear + "-" + startMonthOfYear + "-" + startDayOfMonth;
        }
        queryByDate();
    }

    public void queryByDate(){
        if (beginDateStr != null && endDateStr != null) {
            SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date beginDate = formate.parse(beginDateStr + " 00:00:00");
                Date endDate = formate.parse(endDateStr + " 23:59:59");
                if (beginDate.after(endDate)) {
                    System.out.println("开始日期不得超过结束日期");
                    return;
                }
                Map map = new HashMap();
                map.put("begin", beginDate);
                map.put("end", endDate);
                loadTask(map);// 根据时间段查询数据
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
